<?php

namespace app\common\business;
use \app\common\model\mysql\Role as roleMd;
use think\Exception;

class Role
{
    public function __construct()
    {
        $this->model = new roleMd();
    }

    public function roleGetList()
    {
        $result = $this->model->getSelect([],'id,role_name,desc,role_auth_ids')->toArray();
        if(!$result){
            return false;
        }
        foreach ($result as $key=>$value){
            //查询权限表
            $auths = (new Auth())->getAuthsByRoles([['id','in',$value['role_auth_ids']]])->toArray();
            //再转化伟父子级树状结构图
            $auths = get_tree_list($auths);
            $result[$key]['role_auths'] = $auths;
        }

        return $result;
    }

    public function getRoleById($id)
    {
        //获取用户角色 通过用户id
        $result = (new Admin())->getRoleByUserId($id);
        if(!$result){
            return false;
        }
        $auths = (new Auth())->getAuthsByRoles([['id','in',$result[0]['role']['role_auth_ids']]])->toArray();
        //再转化伟父子级树状结构图
        $auths = get_tree_list($auths);
        $result[0]['role']['role_auths'] = $auths;
        return $result[0]['role'];


    }
    public function roleSave($params)
    {
        $roleName = $params['role_name'];
        $role = $this->model->getSelect([['role_name','=',$roleName]])->toArray();
        if(!empty($role)){
            throw new Exception('角色已经存在');
        }
        $data = [
            'role_name' => $params['role_name'],
            'desc'      => $params['desc'],
            'role_auth_ids' => $params['auth_ids']
        ];
        $roleId = $this->model->insertNewData($data);
        $data['id'] = $roleId;
        return $data;

    }
    public function roleUpdate($params,$id)
    {
        //修改数据
        $this->model->update([
            'role_name' => $params['role_name'],
            'desc'     => $params['desc'],
            'role_auth_ids' => $params['auth_ids']
        ],['id'=>$id]);

        //返回数据
        return $this->model->find($id)->toArray();
    }

    public function roleDelete($id){
        $ids = explode(',',$id);

        //获取用户的角色id  通过$Id
        $AdminRoleIds = (new \app\common\model\mysql\Admin())->getRoleIdById($ids);
        $diffId = array_diff($ids,$AdminRoleIds);
        if(empty($diffId)){
            throw new Exception('有用户正在使用该角色,无法删除');
        }
        try{
            $this->model->destroy($diffId);
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
        return true;



    }
}